<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { FacTaskListType } from '@/api/linePatrol/type'
import { ref, unref, reactive, h } from 'vue'
import { usePatrolGroupStore } from '@/store/modules/PlanGroupStore'
import PlanGroupApi from '@/api/linePatrol/PlanGroupApi'
import EditTask from './EditTask.vue'
import { ElTag } from 'element-plus'
import { useDictStore } from '@/store/modules/dictData'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
const ids = ref<string[]>([])
const GroupStore = usePatrolGroupStore()
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    GroupStore.setGroupDataID(0) //让store发生变化，计划表刷新
    const res = await PlanGroupApi.FacTasklist({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    GroupStore.setGroupDataID(res.rows[0].id)
    return {
      list: res.rows,
      total: res.total
    }
  },
  fetchDelApi: async () => {
    const res = await PlanGroupApi.DeletfacTask(unref(ids)[0])
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
// fac_task_type
const DictStore = useDictStore()
//获取字典
DictStore.setDict('fac_task_state') //任务状态字典
DictStore.setDict('fac_task_type') //任务类型字典
const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'taskName',
    label: t('任务组名称'),
    form: {
      hidden: false,
      colProps: {
        span: 20
      }
    },
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '任务组名称'
      }
    }
  },
  {
    field: 'taskNature',
    label: t('任务性质'),
    form: {
      hidden: false,
      colProps: {
        span: 20
      },
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '巡线',
            value: '巡线'
          }
        ]
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'taskType',
    label: t('运维类型'),
    form: {
      hidden: false,
      colProps: {
        span: 20
      },
      component: 'Select',
      componentProps: {
        options: DictStore.$state.fac_task_type?.map((item) => {
          if (item.dictValue == 'task_type_1') {
            return {
              label: item.dictLabel,
              value: item.dictValue,
              disabled: true
            }
          } else {
            return {
              label: item.dictLabel,
              value: item.dictValue
            }
          }
        })
      }
    },
    search: {
      hidden: true
    },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.fac_task_type?.map((item) => {
        if (item.dictValue == cellValue) {
          return t(item.dictLabel)
        }
      })
    }
  },
  {
    field: 'taskCount',
    label: t('数量'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'taskState',
    label: t('任务组状态'),
    form: {
      component: 'RadioGroup',
      colProps: {
        span: 20
      },
      componentProps: {
        options: DictStore.$state.fac_task_state?.map((item) => {
          return {
            label: item.dictLabel,
            value: Number(item.dictValue)
          }
        })
      }
    },
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        placeholder: '任务组状态',
        options: DictStore.$state.fac_task_state?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.fac_task_state?.map((item) => {
        if (item.dictValue == cellValue) {
          return h(ElTag, { type: item.listClass }, () => t(item.dictLabel))
        }
      })
    }
  },
  {
    field: 'createBy',
    label: t('创建人'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'taskCount',
    label: t('运行中任务'),
    width: 100,
    search: {
      hidden: true
    },
    formatter: (_: Recordable, __: any, cellValue: number) => {
      return h(ElTag, { type: cellValue == 0 ? 'info' : 'success' }, () =>
        cellValue == 0 ? t('不存在') : t('存在')
      )
    },
    table: {
      show: false
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 150,
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn color-[#409eff]" onClick={() => action(data.row, 'edit')}>
                {t('修改')}
              </span>
              <span class="TableBtn color-[#409eff]">{t('复制')}</span>
              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                {t('删除')}
              </span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'taskFaclist',
    label: t('任务清单'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  }
])

const saveLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增任务组')
const EditTaskTypeRef = ref()
const currentRow = ref<FacTaskListType>({})
const actionType = ref('')
//修改提交
const save = async () => {
  const write = unref(EditTaskTypeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    //新增任务组
    if (actionType.value == 'add') {
      res.value = await PlanGroupApi.AddPlanGroupData(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      //修改字
      res.value = await PlanGroupApi.EditPlanGroupData(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
//表格操作
const action = (row: FacTaskListType, type: string) => {
  actionType.value = type
  dialogVisible.value = true //打开弹窗
  currentRow.value = row
  if (type == 'edit') {
    dialogTitle.value = '修改任务组'
  } else {
    dialogTitle.value = '新增任务组'
  }
}
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const delLoading = ref(false)
//删除
const delData = async (row: FacTaskListType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: FacTaskListType) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
//高亮选中
const handleCurrentChange = async (currentRow: FacTaskListType) => {
  if (currentRow) {
    GroupStore.setGroupDataID(currentRow.id)
  }
}
</script>

<template>
  <ContentWrap style="position: relative" :title="t('任务组列表')">
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
      <Icon icon="ep:plus" :size="12" />新增
    </BaseButton>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :highlight-current-row="true"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      @current-change="handleCurrentChange"
    />
    <Dialog style="width: 500px" v-model="dialogVisible" :title="dialogTitle">
      <EditTask
        ref="EditTaskTypeRef"
        :actionType="actionType"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />
      <template #footer>
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('提交') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
      </template>
    </Dialog>
  </ContentWrap>
</template>
<style scoped>
.TableBtn {
  cursor: pointer;
  font-weight: 600;
  margin: 0 5px;
}
:deep(.el-table--default .el-table__cell) {
  padding: 6px 0;
}
.AddbtnStyle {
  margin-bottom: 16px;
  margin-right: 10px;
}
</style>
@/store/modules/PlanGroupApi@/api/linePatrol/PlanGroupApi
